package com.northwest_man.refactor_tool;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.northwest_man.refactor_tool.Constants.*;

// 复制java文件
public class Copy {


    public static void cp() {

        final String[] fileNameWithoutSuffixArray = new String[]{
                "Option"
        };
        for (final String fileNameWithoutSuffix : fileNameWithoutSuffixArray) {
            if (fileNameWithoutSuffix == null || fileNameWithoutSuffix.length() <= 0) continue;
            cp(fileNameWithoutSuffix);
        }
    }

    public static void cp(final String fileNameWithoutSuffix) {
        final File copyFolder = new File(copyParentFolder);
        final File pasteFolder = new File(pastedParentFolder);
        if (!copyFolder.isDirectory() || !pasteFolder.isDirectory()) return;

        final List<String> copyFileList = new ArrayList<>();
        getAllFileInFolder(copyFolder, copyFileList);
        if (debug) {
            for (final String fileName : copyFileList) {
                System.out.println(fileName);
            }
        }
        for (final String fileName : copyFileList) {
            if (fileName.contains("/" + fileNameWithoutSuffix + ".")) {
                final int startIndex = fileName.lastIndexOf(samePath);
                if (startIndex < 0) continue;
                final String pasteFilePath = pastedParentFolder + fileName.substring(startIndex + samePath.length());
                final File pasteFile = new File(pasteFilePath);
                try {
                    FileUtils.copyFile(new File(fileName), pasteFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

        }
    }


    private static void getAllFileInFolder(final File folder, final List<String> fileList) {
        if (!folder.isDirectory()) return;
        final File[] fileInFolder = folder.listFiles();
        if (fileInFolder == null) return;
        for (final File file : fileInFolder) {
            if (file.isDirectory()) {
                getAllFileInFolder(file, fileList);
            } else fileList.add(file.getAbsolutePath());
        }

    }
}
